package au.chao.message.sender;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import org.apache.log4j.Logger;

import au.chao.message.Message;
import au.chao.util.SocketUtil;

public class SocketMessageSender implements Sender {
	private static final Logger log = Logger.getLogger(SocketMessageSender.class);
	private Socket socket;
	Message message = null;

	public SocketMessageSender(Socket socket, Message msg) {
		this.socket = socket;
		message = msg;
	}

	@Override
	public void send() {
		new Thread(this).start();
	}

	@Override
	public void run() {
		ObjectOutputStream objOutStream = null;
		try {
			objOutStream = new ObjectOutputStream(socket.getOutputStream());
			objOutStream.writeObject(message);
		} catch (IOException e) {
			log.error("Send Message error", e);
		} finally {
			SocketUtil.closeSocket(socket);
			SocketUtil.closeIOStream(objOutStream);
		}
	}

}
